package com.xaicode.learn.netty.dubborpc.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.xaicode.learn.support.InetConst.LOCAL_IP;
import static com.xaicode.learn.support.InetConst.PORT_16666;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/20 0020 22:22
 */
@Slf4j
public class NettyClient {

    private static final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static NettyClientHandler clientHandler;

    /**
     * proxy to get class
     *
     * @param serviceClass   public interface service name
     * @param providerPrefix special protocol prefix, like "ClassName#MethodName#"
     * @return proxy class
     */
    public Object getBean(final Class<?> serviceClass, final String providerPrefix) {

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        /*
                            Every time the client is called, it will enter the code block.
                         */

                        // check init
                        if (Objects.isNull(clientHandler)) {
                            initClient();
                        }

                        // set params to server
                        clientHandler.setClientParam(providerPrefix + args[0]);

                        // submit client-handler-callable
                        // and wait if necessary for the computation to complete, and then retrieves its result.
                        return executor.submit(clientHandler).get();
                    }
                });
    }

    // init netty client
    private static void initClient() {
        clientHandler = new NettyClientHandler();

        final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            final Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    // tcp no delay
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            final ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(clientHandler);
                        }
                    });

            final ChannelFuture channelFuture = bootstrap.connect(LOCAL_IP, PORT_16666).sync();
            log.info("netty client started");
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

}
